<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="false" import="java.util.*" language="java" %>
<%@ page import="java.io.InputStream"%>
<%@ page import="org.apache.commons.codec.binary.Base64"%>
<%@ page import="org.mobile.utils.SpringUtil"%>
<%@ page import="com.apexsoft.mobile.module.wskh.flow.service.MediaService"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ page import="java.util.Date"%>
<%@ page import="java.io.ByteArrayOutputStream"%>
<%@ page import="org.mobile.utils.session.Session" %>
<%@ page import="com.apexsoft.mobile.module.common.AppConfig"%>
<%@ page import="net.sf.json.JSONObject"%>
<%!
    private static final String C_FILEPATH_KEY = "CIF_FILEPATH";
%>
<%
	String keytype = request.getParameter("keytype");
	if(null!=keytype&&!"".equals(keytype)){
		Session.setAttribute(request,"keytype",keytype);
	}
    if ("getFILEPATH".equals(request.getParameter("method"))) {
    	// 取filepath
        String FILEPATH  = (String)Session.getAttribute(request,C_FILEPATH_KEY);
        Session.removeAttribute(request,C_FILEPATH_KEY);
        out.clear();
        return;
    }
    // post方法表示已经完成拍照，正在上传文件流中
    if (request.getMethod().toUpperCase().equals("POST")) {
            String fileKey;
            try {
                //保存
                InputStream inputStream = request.getInputStream();
                MediaService mediaSvc = (MediaService)SpringUtil.getBean(request.getServletContext(),"mediaService");
                //ByteArrayOutputStream bos = new ByteArrayOutputStream();
                //byte[] buffer = new byte[2048];
                //int b;
                //while ((b = inputStream.read(buffer)) != -1) {
                //    bos.write(buffer, 0, b);
                //}
				//String mediaBase64 = Base64.encodeBase64String(bos.toByteArray());
				fileKey = mediaSvc.uploadByInputStream(inputStream, new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+".jpg");
			} catch (Exception e) {
                out.println(e.toString());
                return;
            }
			Session.setAttribute(request,AppConfig.YXCJ_KEY, fileKey);
	        // 把filepath存入在session中
            out.print("OK");
        return;
    }

    // 打开拍照动画
    Map params = new HashMap();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        String val = request.getParameter(name);
        if (val != null) {
            val = new String(val.getBytes(), "GBK");
        }
        params.put(name, val);

    }
    Session.setAttribute(request,"CIF_CAP_PARAMS", params);

    String swfParams = null;
    if (params != null) {
        swfParams = (String) params.get("swfParams");
    }
    if (swfParams != null) {
        try {
            swfParams = java.net.URLDecoder.decode(swfParams, "utf-8");
        } catch (Exception e) {
            swfParams = null;
        }
    }
   out.clear();
%>
<html>
<head><title>自拍头像</title>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
//获取falsh版本号
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion(){
        var version;
        var axo;
        var e;

        // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

        try {
                // version will be set for 7.X or greater players
                axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
                version = axo.GetVariable("$version");
        } catch (e) {
        }

        if (!version)
        {
                try {
                        // version will be set for 6.X players only
                        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
                        
                        // installed player is some revision of 6.0
                        // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
                        // so we have to be careful. 
                        
                        // default to the first public version
                        version = "WIN 6,0,21,0";

                        // throws if AllowScripAccess does not exist (introduced in 6.0r47)                
                        axo.AllowScriptAccess = "always";

                        // safe to call for 6.0r47 or greater
                        version = axo.GetVariable("$version");

                } catch (e) {
                }
        }

        if (!version)
        {
                try {
                        // version will be set for 4.X or 5.X player
                        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
                        version = axo.GetVariable("$version");
                } catch (e) {
                }
        }

        if (!version)
        {
                try {
                        // version will be set for 3.X player
                        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
                        version = "WIN 3,0,18,0";
                } catch (e) {
                }
        }

        if (!version)
        {
                try {
                        // version will be set for 2.X player
                        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
                        version = "WIN 2,0,0,11";
                } catch (e) {
                        version = -1;
                }
        }
        var verArr = version.toString().split(',');
        var str = '';
        for(var i=0,l=verArr.length;i<l;i++){
                
                if(verArr[i].indexOf('WIN') != -1){
                        str += verArr[i].substring(3);
                        str += '.';
                }else if(i== (l-1)){
                        str += verArr[i];
                }else{
                        str += verArr[i];
                        str += '.';        
                }
                
        }
        return (str);
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
        // NS/Opera version >= 3 check for Flash plugin in plugin array
        var flashVer = -1;
        
        if (navigator.plugins != null && navigator.plugins.length > 0) {
                if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
                        var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
                        var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
                        var descArray = flashDescription.split(" ");
                        var tempArrayMajor = descArray[2].split(".");                        
                        var versionMajor = tempArrayMajor[0];
                        var versionMinor = tempArrayMajor[1];
                        var versionRevision = descArray[3];
                        if (versionRevision == "") {
                                versionRevision = descArray[4];
                        }
                        if (versionRevision[0] == "d") {
                                versionRevision = versionRevision.substring(1);
                        } else if (versionRevision[0] == "r") {
                                versionRevision = versionRevision.substring(1);
                                if (versionRevision.indexOf("d") > 0) {
                                        versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
                                }
                        }
                        var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
                        //alert("flashVer="+flashVer);
                }
        }
        // MSN/WebTV 2.6 supports Flash 4
        else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
        // WebTV 2.5 supports Flash 3
        else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
        // older WebTV supports Flash 2
        else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
        else if ( isIE && isWin && !isOpera ) {
                flashVer = ControlVersion();
        }        
        return String($.trim(flashVer));
}
</script>
    <style type="text/css">
        body {
            margin: 0;
            padding: 0;
            text-align: center;
            font-size: 12px;
        }
    </style>
    <script type="text/javascript">
        <%
           String cokid = "CAM_" + ("" + params.get("$FILE_NAME"));
           int CAMERA_INDEX = 0;
           Cookie[] cookies = request.getCookies();
           for(Cookie cookie: cookies){
             if(cookie != null && cookie.getName().equals(cokid)){
               try {
                    CAMERA_INDEX = Integer.parseInt(cookie.getValue());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
               break;
            }
          }

        %>
        MediaUtil = {};
        //写cookies函数
        MediaUtil.setCookie = function (name, value, days)//两个参数，一个是cookie的名子，一个是值
        {
            var Days = days || 365 * 10; //此 cookie 将被保存10年 天
            var exp = new Date();    //new Date("December 31, 9998");
            exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
            document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
        };
        MediaUtil.getCookie = function (name)//取cookies函数
        {
            var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
            if (arr != null) return unescape(arr[2]);
            return null;
        };

        var CAMERA_TYPE_ID = "<%=cokid%>";
        var CameraChange=function(idx,name,cam){
            MediaUtil.setCookie(CAMERA_TYPE_ID,idx);
        };
        var DoCancel = function() {
            window.close();
            window.parent.close();
        };
        var DoOK = function() {
            window.returnValue = window.parent.returnValue = {ret:1,msg:'OK',ID:-100};
            window.close();
            window.parent.close();
        };
        $(function(){
        /**********
			if (parseFloat(GetSwfVer()) < parseFloat('11.8.800.99')) {//数值可以调节
			    alert('flash player当前版本为' + GetSwfVer() + '，版本过低\r\n请安装不低于10.2的版本,安装完后重启浏览器生效！');
			    window.location.href ='http://get.adobe.com/cn/flashplayer/';
			}
		**********/
			//数组排序比较大小
			var version=GetSwfVer();
			var ee = new Array(version,'10.2');
			var mm =ee.sort();
			if (mm[0] === version) {//数值可以调节
				alert('flash player当前版本为' + version + '，版本过低\r\n请安装不低于10.2的版本,安装完后重启浏览器生效！');
		    	window.location.href ='http://get.adobe.com/cn/flashplayer/';
			}
		});
</script>
</head>
<body>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
        id="camera" width="670" height="520"
        codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
    <param name="movie"
           value="<%=request.getContextPath()%>/plug-in/cif2/camera.swf?CROP_ENABLED=true&CROP_BORDER=3&CROP_RESIZABLE=true&CROP_HEIGHT=475&CROP_WIDTH=635&SIZE_INDEX=8&CAMERA_INDEX=<%=CAMERA_INDEX%><%=swfParams==null?"":"&"+swfParams%>"/>
    <param name="quality" value="high"/>
    <param name="bgcolor" value="#869ca7"/>
    <param name="allowFullscreen" value="true"/>
    <param name="allowScriptAccess" value="always"/>
    <embed src="<%=request.getContextPath()%>/plug-in/cif2/camera.swf?CROP_ENABLED=true&CROP_BORDER=3&CROP_RESIZABLE=true&CROP_HEIGHT=475&CROP_WIDTH=635&SIZE_INDEX=8&CAMERA_INDEX=<%=CAMERA_INDEX%><%=swfParams==null?"":"&"+swfParams%>"
           quality="high" bgcolor="#869ca7"
           width="670" height="520" name="camera" align="middle"
           play="true"
           loop="false"
           quality="high"
           allowScriptAccess="always"
           type="application/x-shockwave-flash"
           pluginspage="http://www.adobe.com/go/getflashplayer">
    </embed>
</object>
</body>
</html>
